#include <config.h>

#include <notification_sender.h>
#include <configuration.h>
#include <process_struct.h>

#include <libnotify/notify.h>
#include <glibmm/ustring.h>
using Glib::ustring;
#include <glibmm/i18n.h>

#include <iomanip>
using std::setprecision;
using std::fixed;
#include <iostream>
using std::cerr;
using std::endl;

notification_sender::notification_sender (const configuration &nconfig):
config_ (nconfig),
notification_ (NULL)
{
    notify_init (PACKAGE_NAME);
}

notification_sender::~notification_sender (){
    notify_uninit ();
}

void notification_sender::process_added (const process_t &process){
    if (!config_.enable_notification) return;
    /* construct notify text */
    ustring summary;
    ustring text;
    if (process.cpu > config_.cpu_valve) {
        summary = _("CPU Warning");
        text = ustring::compose (_("%1 consumes %2%% CPU"),
                process.name,
                ustring::format (setprecision (1), fixed, process.cpu));
    } else if (process.memory > config_.memory_valve) {
        summary = _("Memory Warning");
        text = ustring::compose (_("%1 consumes %2mb memory"),
                process.name,
                ustring::format (setprecision (1), fixed, process.memory));
    } else if (process.read_bytes > config_.io_valve) {
        if (config_.disable_io_notification) return;
        summary = _("IO Warning");
        text = ustring::compose (_("%1 is reading disk at %2mb/s"),
                process.name,
                ustring::format (setprecision (1), fixed, process.read_bytes));
    } else if (process.write_bytes > config_.io_valve) {
        if (config_.disable_io_notification) return;
        summary = _("IO Warning");
        text = ustring::compose (_("%1 is writing disk at %2mb/s"),
                process.name,
                ustring::format (setprecision (1), fixed, process.write_bytes));
    } else {
        cerr << "sending normal process to notification: " << process.name
             << endl;
        return;
    }

    /* TODO
     * add a notification_ icon here */
    if (!notification_){
        notification_ = notify_notification_new (
                summary.c_str(), text.c_str(), NULL, NULL);
        notify_notification_show (notification_, NULL);
    } else {
        notify_notification_update (
                notification_, summary.c_str(), text.c_str(), NULL);
        notify_notification_show (notification_, NULL);
    }
}
